package com.fingard.dsp.bank.directbank.xwbank02;

import java.util.Calendar;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IQryRefund;
import com.fingard.dsp.bank.reqrespobj.qryrefund.ReqQryRefund;
import com.fingard.dsp.bank.reqrespobj.qryrefund.RetAtsQryRefund;
import com.fingard.dsp.bank.reqrespobj.qryrefund.detail.RetAtsRefundDetail;
import com.fingard.text.StringHelper;
import com.xwbank.sdk.XWBankPay;
import com.xwbank.sdk.entity.QueryRefundInfo;

public class XWBank02QryRefund extends XWBank02Base implements IQryRefund {
	@Override
	public RetAtsQryRefund d_qry_refund(ReqQryRefund p_req) throws Exception {
		RetAtsQryRefund retAts = new RetAtsQryRefund(p_req.reqHeader);
        retAts.writeStart();

        String tmpRespCode = "";
        String tmpRespInfo = "";
        
        int tmpSuccCount = 0;
        double tmpTotalAmt = 0.00;

        try {
        	Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req.getQryStartDate());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req.getQryEndDate());
            tmpCalendarTo.add(Calendar.DAY_OF_MONTH, 1);
            
            while (tmpCalendarFrom.compareTo(tmpCalendarTo) == -1) {
            	String propertiesPath = getBankConfig().getValueAsString("propertiesPath");
    			String merchantId = getBankConfig().getValueAsString("merchantId");
    			String ownKeyStorePath = getBankConfig().getValueAsString("ownKeyStorePath");
    			if (StringHelper.isNullOrEmpty(propertiesPath) || StringHelper.isNullOrEmpty(merchantId) || StringHelper.isNullOrEmpty(ownKeyStorePath)) {
    				 retAts.writeRespCode("-1");
		             retAts.writeRespInfo("缺失'propertiesPath/merchantId/ownKeyStorePath'配置或节点内容为空!");
		             retAts.writeEnd();
		             return retAts;
    			}
    			
    			boolean initSuccess = XWBankPay.init(getConfigPath(propertiesPath), getConfigPath(ownKeyStorePath));
    			if (!initSuccess) {
    				 retAts.writeRespCode("-1");
		             retAts.writeRespInfo("config.properties配置有误!");
		             retAts.writeEnd();
		             return retAts;
    			}
        		
        		QueryRefundInfo queryRefundRequest = new QueryRefundInfo();
        		
        		queryRefundRequest.setVersion("1.0");
        		String qryRefundDate = Format.Date8Format.format(tmpCalendarFrom.getTime());
        		queryRefundRequest.setRefund_date(qryRefundDate);
        		queryRefundRequest.setSource_type("");
        		queryRefundRequest.setConsumer_id("");
        		queryRefundRequest.setMcht_no(merchantId);
        		
        		writeBankLogStep2(queryRefundRequest);
        		
        		Map<String, Object> tmpMapRet = XWBankPay.getInstance().queryRefund(queryRefundRequest);
        		
        		writeBankLogStep3(tmpMapRet);
        		
        		if (tmpMapRet != null) {
        			String returnCode = (String) tmpMapRet.get("returnCode");
        			if ("000000".equals(returnCode)) {
        				tmpRespCode = "0";
        				
        				String tmpStrRet = (String) tmpMapRet.get("data");
        				WriteBankLogLn2("银行返回退票明细:\r\n" + tmpStrRet);
        				JSONArray tmpRespJsonArr = JSONArray.parseArray(JSONObject.parseObject(tmpStrRet).getString("refundRecords"));
        				 if(tmpRespJsonArr.size() > 0) {
        					 for(int i = 0; i < tmpRespJsonArr.size(); i++) {
        						 tmpSuccCount++;
        						 
        						 JSONObject jsonDetail = tmpRespJsonArr.getJSONObject(i); 
        						 RetAtsRefundDetail tmpRetDetail = new RetAtsRefundDetail();
        						 
        						 String refundAmt = jsonDetail.getString("refund_amt");
        						 if (StringHelper.hasAnyChar(refundAmt)) {
        							 tmpTotalAmt += Double.parseDouble(refundAmt);
        						 }
    		                     tmpRetDetail.askNum = jsonDetail.getString("orig_serial_no");
    		                     tmpRetDetail.recAct = jsonDetail.getString("orig_payee_acct_no");
    		                     String refundDate = Format.Date10Format.format(Format.Date8Format.parse(jsonDetail.getString("refund_date")));
    		                     tmpRetDetail.refundTicketDate = refundDate;
    		                     tmpRetDetail.submitTime = refundDate;
    		                     tmpRetDetail.amount = refundAmt;

    		                    retAts.writeRetDetailOnly(tmpRetDetail);
        					 }
        				 } else {
        					 tmpRespCode = "-1";
                 			 tmpRespInfo = qryRefundDate + "日期内无退票数据!";
        				 }
        			} else {
        				tmpRespCode = "-1";
            			tmpRespInfo = (String) tmpMapRet.get("returnMsg");
        			}
        		} 
                
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
            }
            
            retAts.totleNum = String.valueOf(tmpSuccCount);
            retAts.totleAmount = Format.DecimalAmtFormat.format(tmpTotalAmt);
            retAts.writeTotalInfo();
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } 

        retAts.writeEnd();
        return retAts;
	}
}
